<?php
// Turn off PHP notices for now:
error_reporting(E_ALL & ~E_NOTICE);

// Check if SQlite extension was loaded
if (!extension_loaded('sqlite')) {
  // dl dynamic loading was removed in newest PHP version
  //if (!dl('php_sqlite.dll')) {
  die('Please enable the "php_sqlite" extension in your PHP installation: Wamp Icon -> PHP -> PHP Extensions -> php_sqlite');
  //}
}

// Define various constants []:
define('THFRPATH', dirname(__FILE__) . '/');
define('THFRDIRNAME', basename(THFRPATH));

define('THFRURL', '/');
define('RELATIVETHFRURL', '/');
define('THFRUPLOADPATH', THFRPATH . 'uploads');
define('RELATIVETHFRUPLOADURL', RELATIVETHFRURL . 'uploads/');
define('THFRUPLOADURL', RELATIVETHFRURL . 'uploads/');

//define Drop areas & zones
/*
 * Ii you will add some zones do not forget also add them in themeframe.js and themeframe.css
 */
$aAvailableDropAreas = $aAvailableDropZones = array(
  'header',
  'centerTop',
  'beforePost',
  'beforePostTitle',
  'afterPostTitle',
  'afterThumbnail',
  'afterPost',
  'centerBeforeComments',
  'centerBottom',
  'footer',
  'beforeSidebarLeft',
  'afterSidebarLeft',
  'beforeSidebarRight',
  'afterSidebarRight',
);
$aAvailableDropZones[] = 'drop';

// Checks if table XY exists
function sqlite_table_exists(&$sqlite, $table) {
  $result = $sqlite->query("SELECT name FROM sqlite_master WHERE type='table' AND name='$table'");
  return $result->numRows() > 0;
}

// Check if DB "thfrdb" exists, else create it or display error
if ($db = new SQLiteDatabase(dirname(__FILE__) . '/sqlite/thfrdb.sqlite')) {
  // Create table if not exists
  // node is not integer, can be string like "4.2.3.1.2"
  if (sqlite_table_exists($db, 'newdefault') === FALSE) {
    $db->queryExec('CREATE TABLE newdefault (id INTEGER, option_name TEXT, option_value TEXT, node TEXT, branch INTEGER, step INTEGER, PRIMARY KEY (id));');

    // Fill table with default settings
    $thfr_css_serialized = file_get_contents(THFRPATH . 'styles/default.txt');
    $thfr_css_prepared = sqlite_escape_string($thfr_css_serialized);
    $db->queryExec("INSERT into newdefault (option_name, option_value, node, branch, step) values ('thfr','$thfr_css_prepared', '0', '0', '0');");
  }

  // Create 2nd table where current position in undo/redo history will be saved:
  if (sqlite_table_exists($db, 'newdefault_curpos') === FALSE) {
    $db->queryExec('CREATE TABLE newdefault_curpos (id INTEGER, node TEXT, branch INTEGER, step INTEGER, PRIMARY KEY (id));');
    $db->queryExec('INSERT into newdefault_curpos (node, branch, step) values (0, 0, 0);');
  }
} else {
  die($err);
}

$thfr_css = get_thfr();

// Default settings
/*
if ( !isset($thfr_css['savedonce']) ) {
  $thfr_css = unserialize(file_get_contents(THFRPATH . 'styles/default.txt'));
}
*/

function get_curpos() {

  global $db;

  $result = $db->query("SELECT node, branch, step FROM newdefault_curpos LIMIT 1;");

  $row = $result->current();
  $curpos = array(
    'node' => $row['node'],
    'branch' => $row['branch'],
    'step' => $row['step']
  );

  return $curpos;
}

function get_lastpos() {

  global $db;

  $result = $db->query("SELECT node, branch, step FROM newdefault where oid = (select max(oid) from newdefault);");

  $row = $result->current();
  $lastpos = array(
    'node' => $row['node'],
    'branch' => $row['branch'],
    'step' => $row['step']
  );

  return $lastpos;
}

function set_curpos($node, $branch, $step) {

  global $db;

  $db->queryExec("UPDATE newdefault_curpos SET node='$node', branch='$branch', step='$step';");

  return;
}

function next_step_exists() {

  global $db;

  $curpos = get_curpos();
  $node = $curpos['node'];
  $branch = $curpos['branch'];
  $step = $curpos['step'];

  $next_step = $step + 1;
  $result = $db->query("SELECT id FROM newdefault WHERE node='$node' AND branch='$branch' AND step='$next_step';");
  $rows = $result->numRows();

  if ($rows > 0) {
    return TRUE;
  } else {
    return FALSE;
  }
}

function get_branch() {

  global $db;

  $curpos = get_curpos();
  $node = $curpos['node'];
  $branch = $curpos['branch'];
  $step = $curpos['step'];

  // Existing branches originating would have a node name like 'node.branch.step':
  $child_node = $node . '.' . $branch . '.' . $step;

  // Get number of existing branches that originated from this node
  $result = $db->query("SELECT id FROM newdefault WHERE node='$child_node' AND step='1';");
  $rows = $result->numRows();

  return $rows + 1;
}

function get_thfr() {

  global $db;

  $curpos = get_curpos();
  $node = $curpos['node'];
  $branch = $curpos['branch'];
  $step = $curpos['step'];

  $result = $db->query("SELECT option_value FROM newdefault WHERE node='$node' AND branch='$branch' AND step='$step' LIMIT 1;");

  $row = $result->current();

  return (unserialize($row[0]));
}

function set_thfr($message = '', $save = 1, $import_file = '') {
  global $db, $thfr_css;

  if ($import_file != '') {
    $thfr_css_serialized = file_get_contents($import_file);
  } else {
    $thfr_css_serialized = serialize($thfr_css);
  }

  $curpos = get_curpos();
  $node = $curpos['node'];
  $branch = $curpos['branch'];
  $step = $curpos['step'];

  if ($save == 1) {
    $thfr_css_prepared = sqlite_escape_string($thfr_css_serialized);

    // If a next step exists in the current branch, start a new branch, to preserve those next steps for REDO's in the current branch
    if (next_step_exists()) {
      $node = $node . '.' . $branch . '.' . $step; // Create a new branch from current node, e.g. '4.2.1'
      $branch = get_branch(); // [number of existing branches for this node] + 1
      $step = 1; // Step is 1 because we're starting a new branch
    } else {
      $step = $step + 1; // increment step +1 and stay with current node & branch
    }

    $db->queryExec("INSERT into newdefault (option_name, option_value, node, branch, step) values ('thfr','$thfr_css_prepared', '$node', '$branch', '$step');");

    set_curpos($node, $branch, $step);
  }

  // Success message and history position
  $all_messages = array(
    'message' => $message,
    'node' => $node,
    'branch' => $branch,
    'step' => $step
  );

  // Send messages to jQuery
  echo json_encode($all_messages);

  return;
}

function undo_thfr() {

  #global $db;


  $curpos = get_curpos();
  $node = $curpos['node'];
  $branch = $curpos['branch'];
  $step = $curpos['step'];

  $message = "You went 1 step BACK...";

  /*
    if ( $step == "1" ) {
      if ( $node == "0" ) {
        // Node = 0, Step = 1
        $message = "No UNDO steps left...";
      } else {
        // Node > 1, Step = 1: If we're at a branch's first step, 1 step back means back to the parent node
        $pieces = explode('.', $node);
        $node = $pieces[0];
        $branch = $pieces[1];
        $step = $pieces[2];
      }
    } else {
      $step = $step - 1;
    }
  */

  // Since RC1c: (Could not go back 1 step to 0-0-0:
  if ($step == "0" and $node == "0") {
    $message = "No UNDO steps left...";
  } else if ($step == "1" and $node != "0") {
    // Node > 1, Step = 1: If we're at a branch's first step, 1 step back means back to the parent node
    $pieces = explode('.', $node);
    if (count($pieces) >= 5) {
      $step = array_pop($pieces); // last is step
      $branch = array_pop($pieces); // now last is branch
      $node = implode('.', $pieces); // combine rest to create node
    } else {
      $node = $pieces[0];
      $branch = $pieces[1];
      $step = $pieces[2];
    }
  } else {
    $step = $step - 1;
  }

  set_curpos($node, $branch, $step);

  // Success message and history position
  $all_messages = array(
    'message' => $message,
    'node' => $node,
    'branch' => $branch,
    'step' => $step
  );

  // Send messages to jQuery
  echo json_encode($all_messages);

  return;
}

function undo_thfr_all() {

  #global $db;


  $node = '0';
  $branch = '0';
  $step = '0';

  $message = "You UNDID ALL changes...";

  set_curpos($node, $branch, $step);

  // Success message and history position
  $all_messages = array(
    'message' => $message,
    'node' => $node,
    'branch' => $branch,
    'step' => $step
  );

  // Send messages to jQuery
  echo json_encode($all_messages);

  return;
}

/*
If there are branches starting from the current node, a redo will step into the newest branch
To move into an older branch, the history can be viewed, and indivual history nodes can be chosen from there
*/
function redo_thfr() {

  #global $db;


  $curpos = get_curpos();
  $node = $curpos['node'];
  $branch = $curpos['branch'];
  $step = $curpos['step'];

  $message = "You went 1 step FORWARD...";

  // If branch exists, go forward to step 1 of the highest branch number (= newest branch)
  // 1 = no branch exists yet
  if (get_branch() !== 1) {
    $node = $node . '.' . $branch . '.' . $step;
    # $branch = get_branch();
    // Since RC1b:
    $branch = get_branch() - 1;
    $step = 1;
    // No branch from this node, but next step exists
  } else if (next_step_exists()) {
    $step = $step + 1;
  } else {
    $message = "No REDO steps left...";
  }

  set_curpos($node, $branch, $step);

  // Success message and history position
  $all_messages = array(
    'message' => $message,
    'node' => $node,
    'branch' => $branch,
    'step' => $step
  );

  // Send messages to jQuery
  echo json_encode($all_messages);

  return;
}

function redo_thfr_all() {

  $lastpos = get_lastpos();
  $node = $lastpos['node'];
  $branch = $lastpos['branch'];
  $step = $lastpos['step'];

  set_curpos($node, $branch, $step);

  $message = "You REDID ALL changes...";

  // Success message and history position
  $all_messages = array(
    'message' => $message,
    'node' => $node,
    'branch' => $branch,
    'step' => $step
  );

  // Send messages to jQuery
  echo json_encode($all_messages);

  return;
}

function reset_thfr() {

  global $db;

  $thfr_css = unserialize(file_get_contents(THFRPATH . 'styles/default.txt'));
  $thfr_css_serialized = serialize($thfr_css);
  $thfr_css_prepared = sqlite_escape_string($thfr_css_serialized);

  $db->queryExec("UPDATE newdefault SET option_value = '$thfr_css' WHERE option_name = 'thfr';");

  if ($db->changes() == 0) {
    $db->queryExec("INSERT into newdefault (option_name, option_value) values ('thfr','$thfr_css');");
  }

  echo "Settings have been reset...";

  return;
}

function history_clear() {

  global $db, $thfr_css;

  $db->queryExec("DROP TABLE newdefault;");
  $db->queryExec('CREATE TABLE newdefault (id INTEGER, option_name TEXT, option_value TEXT, node TEXT, branch INTEGER, step INTEGER, PRIMARY KEY (id));');

  $thfr_css_serialized = serialize($thfr_css);
  $thfr_css_prepared = sqlite_escape_string($thfr_css_serialized);

  $db->queryExec("INSERT into newdefault (option_name, option_value, node, branch, step) values ('thfr','$thfr_css_prepared', '0', '0', '0');");

  set_curpos('0', '0', '0');

  // Shrink DB after the table was deleted, or else it'll be bigger than necessary: http://www.sqlite.org/lang_vacuum.html
  $db->queryExec("VACUUM;");

  $message = "History has been cleared...";

  // Success message and history position
  $all_messages = array(
    'message' => $message,
    'node' => '0',
    'branch' => '0',
    'step' => '0'
  );

  // Send messages to jQuery
  echo json_encode($all_messages);

  return;
}

function history_view() {

  global $db;

  $curpos = get_curpos();
  $node = $curpos['node'];
  $branch = $curpos['branch'];
  $step = $curpos['step'];

  $result = $db->query("SELECT id, node, branch, step FROM newdefault ORDER BY node, branch, step ASC;");

  $string = '<br />History displayed as <code>"ID. <span style="text-decoration:underline">Node-Branch-Step</span>"</code>. <span style="color:red">RED</span> = Your current position. Click any history point to jump there.<br /><ul id="historyview">';

  while ($r = $result->fetch()) {
    $opentag = '';
    $closetag = '';

    if ($r['node'] == $node and $r['branch'] == $branch and $r['step'] == $step) {
      $opentag = '<span style="color:red">';
      $closetag = '</span>';
    }

    $string .= '<li><code>' . $r['id'] . '. <a href="#" node="' . $r['node'] . '" branch="' . $r['branch'] . '" step="' . $r['step'] . '">' . $opentag . $r['node'] . '-' . $r['branch'] . '-' . $r['step'] . $closetag . '</a></code></li>';
  }

  $string .= '</ul>A multi-digit node such as <code>0.0.4</code> means this was branched out from <code>0-0-4</code>';

  return $string;
}

function history_set() {

  global $db;

  $curpos = get_curpos();
  $node = $_POST['node'];
  $branch = $_POST['branch'];
  $step = $_POST['step'];

  set_curpos($node, $branch, $step);

  $message = "You jumped to " . $node . "-" . $branch . "-" . $step . " ...";

  // Success message and history position
  $all_messages = array(
    'message' => $message,
    'node' => $node,
    'branch' => $branch,
    'step' => $step
  );

  // Send messages to jQuery
  echo json_encode($all_messages);

  return $string;
}

function delete_drop_item() {
  global $thfr_css, $aAvailableDropZones;

  $itemgroup = $_POST['itemgroup'];
  $itemname = $_POST['itemname'];

  switch ($itemgroup) {
    case "customdroplinks":
      $extension = '_custlink';
      break;
    case "customdropimages":
      $extension = '_custimg';
      break;
    case "customdropdivs":
      $extension = '_custdiv';
      break;
  }

  $dropitemname = $itemname . $extension;

  if (isset($thfr_css[$itemgroup][$itemname])) {
    unset($thfr_css[$itemgroup][$itemname]);
  }

  foreach ($thfr_css['pagetemplates'] as $template) {
    $newdroparea = array();
    foreach ($aAvailableDropZones as $droparea) {
      $newdroparea[$droparea] = array();
      $i = 0;
      while ($thfr_css[$template][$droparea . '-' . $i] != '') {
        if ($thfr_css[$template][$droparea . '-' . $i] != $dropitemname) {
          $newdroparea[$droparea][] = $thfr_css[$template][$droparea . '-' . $i];
        }
        $i++;
      }
      // Clear all existing values:
      for ($i = 0; $i < 31; $i++) {
        if (isset($thfr_css[$template][$droparea . '-' . $i])) {
          unset($thfr_css[$template][$droparea . '-' . $i]);
        }
      }
      // Create new values:
      $i = 0;
      foreach ($newdroparea[$droparea] as $dropitem) {
        $thfr_css[$template][$droparea . '-' . $i] = $dropitem;
        $i++;
      }
    }
  }

  $message = $itemname . " has been deleted...";
  set_thfr($message);

  return;
}

function delete_page_template() {

  global $thfr_css;

  $tplname = $_POST['tplname'];

  // remove item by value
  if (in_array($tplname, $thfr_css['pagetemplates'])) {
    $thfr_css['pagetemplates'] = array_diff($thfr_css['pagetemplates'], array(
      $tplname
    ));
  }

  // remove this too
  if (isset($thfr_css[$tplname])) {
    unset($thfr_css[$tplname]);
  }

  $message = $tplname . ".php has been deleted...";
  set_thfr($message);

  return;
}

/**********************************************************
CHECK THIS
 ****************************/

function tf_new_postcontainer($newPostContainer, $model) {

  global $thfr_css;

  if (isset($thfr_css['postcontainers'][$model])) {
    if (isset($thfr_css['postcontainers'][$newPostContainer])) {
      echo "<span style='color:green'>Successfully created new post container type '$newPostContainer'</span>";
      return;
    } else {
      $thfr_css['postcontainers'][$newPostContainer] = $thfr_css['postcontainers'][$model];
      set_thfr();
      echo "<span style='color:green'>Successfully created new post container type '$newPostContainer'</span>";
      return;
    }
  }

  echo "The post container '$model' does not exist";

  return;
}

function file_extension($filename) {

  $path_info = pathinfo($filename);

  return $path_info['extension'];
}

function obj_dump($var) {
  if (function_exists('debug_backtrace')) {
    $Tmp1 = debug_backtrace();
  } else {
    $Tmp1 = array(
      'file' => 'UNKNOWN FILE',
      'line' => 'UNKNOWN LINE',
    );
  }
  echo "<FIELDSET STYLE=\"font:normal 12px helvetica,arial; margin:10px;\"><LEGEND STYLE=\"font:bold 14px helvetica,arial\">Dump - " . $Tmp1[0]['file'] . " : " . $Tmp1[0]['line'] . "</LEGEND><PRE>\n";
  echo htmlspecialchars(print_r($var, true));
  echo "</PRE></FIELDSET>\n\n";
}

function update_unternal_css() {
  global $thfr_css;

  get_thfr();

  $sels = tf_selectors();
  $i = 0;
  $new_keys = array();
  foreach ($thfr_css as $key => $value) {
    if (in_array($key, $sels)) {
      $new_keys[] = $thfr_css['internal_css'][$key] = $thfr_css[$key];
      unset($thfr_css[$key]);
      $i++;
    }
  }
  if ($i > 0) {
    //    obj_dump($new_keys);
    set_thfr('');
    //unset old values  
    unset($thfr_css['td#td-header']);
    unset($thfr_css['a.facebooklink']);
    unset($thfr_css['a.twitterlink']);
    unset($thfr_css['a.feedburnerlink']);
    unset($thfr_css['td#td-left']);
    unset($thfr_css['td#td-right']);
    unset($thfr_css['td#td-left2']);
    unset($thfr_css['td#td-right2']);
    unset($thfr_css['div.home div.breadcrumbs']);
    unset($thfr_css['div.home div.searchform form input.searchfield']);
    unset($thfr_css['div#div-center']);
    unset($thfr_css['div.post-headline h2']);
    unset($thfr_css['div#div-header']);
    unset($thfr_css['div.post-headline h2 a']);
    unset($thfr_css['div.single div#div-center']);
    unset($thfr_css['div.single div#div-center']);
    unset($thfr_css['']);
  }
}

include (THFRPATH . 'includes/tf_create_css_code.php');
include (THFRPATH . 'includes/tf_create_php_file.php');
include (THFRPATH . 'includes/tf_create_php_file_comments.php');
include (THFRPATH . 'includes/tf_create_functions_file.php');
include (THFRPATH . 'includes/tf_create_header_file.php');
include (THFRPATH . 'includes/tf_import_settings_now.php');
include (THFRPATH . 'includes/tf_print_css_code.php');
include (THFRPATH . 'includes/tf_print_form.php');
include (THFRPATH . 'includes/tf_print_js.php');
include (THFRPATH . 'includes/tf_save_options.php');
include (THFRPATH . 'includes/tf_pagetemplate.php');
include (THFRPATH . 'includes/tf_pagetemplate_include.php');
include (THFRPATH . 'includes/tf_common_template_sections.php');
include (THFRPATH . 'includes/tf_common_examples_template.php');
include (THFRPATH . 'includes/tf_drop_area.php');
include (THFRPATH . "includes/tf_selectors.php");
include (THFRPATH . "includes/zip.lib.php");
include (THFRPATH . "includes/tf_ftp_transfer.php");
include (THFRPATH . "includes/tf_postcontainer_preview.php");
include (THFRPATH . "includes/tf_postcontainer_code.php");

include (THFRPATH . "includes/tf_custom_drop_image.php");
include (THFRPATH . "includes/tf_custom_drop_link.php");
include (THFRPATH . "includes/tf_custom_drop_div.php");

include (THFRPATH . "includes/tf_get_used_colors.php");

if (is_dir($thfr_css['wp_path'])) {
  define('WP_USE_THEMES', false);
  /** Loads the WordPress Environment and Template */
  //require($thfr_css['wp_path'] . 'wp-load.php');
}

//obj_dump($thfr_css);

update_unternal_css();

# when using later (move from pagetemplate.php) define $body_class
#include(THFRPATH . 'functions/tf_page_items.php');
#include(THFRPATH . "selectors.php");

// Since Beta 20
if ($thfr_css['commenttext']['dontloaddirectly'] == '') {
  include (THFRPATH . "includes/tf_get_comment_bits.php");
}
?>